// pages/classification/index.js
const {
  get
} = getApp();
Page({
  // 数据
  data: {
    activeKey: 0,
    cat_list: [],
    goodsList: [],
    activeName: '',
    params: {
      page: 1,
      pageSize: 20,
      cat_id: 0
    },
    showPage: false,
    showLoading: true
  },
  // 跳转详情
  goToCommodity: function (e) {
    wx.navigateTo({
      url: `../commodity/index?unique_id=${e.currentTarget.dataset.unique_id}`,
    })
  },
  //  初始化加载
  onLoad: function () {
    get("/cat/list").then(res => {
      if (res.result == 1) {
        this.setData({
          "cat_list": res.data,
          "activeName": res.data[0].name,
          "params.cat_id": res.data[0].cat_id
        });
        this.getCatList(res.data[0].cat_id);
      }
    })
  },
  // 获取分类商品
  getCatList() {
    if (this.data.showLoading) {
      get(`/cat/goods-list`, this.data.params).then(res => {
        if (res.result == 1) {
          if (res.data.length < this.data.params.pageSize) {
            this.setData({
              goodsList: this.data.goodsList.concat(res.data),
              showLoading: false,
              showPage: true
            })
          } else {
            this.setData({
              goodsList: this.data.goodsList.concat(res.data),
              showPage: true
            })
          }
        }
      })
    }
  },
  // 切换
  changeCat(e) {
    if(!this.data.showPage){
      return;
    };
    if (e.currentTarget.dataset.cat_id == this.data.activeKey) {
      return;
    };
    this.setData({
      "activeKey": e.currentTarget.dataset.cat_id,
      "activeName": e.currentTarget.dataset.name,
      "params.cat_id": e.currentTarget.dataset.cat_id,
      "params.page": 1,
      "goodsList": [],
      "showLoading": true,
      "showPage": false
    });
    this.getCatList();
  },
  // 到底部事件
  bindscrolltolower() {
    if (this.data.showLoading) {
      this.setData({
        "params.page": this.data.params.page += 1
      });
      this.getCatList();
    };
  },
  // tabBar展示
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    };
    // 控制分享按钮
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success(res) {
        console.log('showShareMenu', res);
      }
    })
  }
})